package com.qianfeng.sks.findingfood.utils;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.sks.findingfood.adapter.AppBaseAdapter;
import com.qianfeng.sks.findingfood.bean.AppBean;

import java.util.List;

/**
 * Created by sks on 15-7-9.
 * xutils封装异步封装工具
 */
public class HttpTools {
    private static HttpUtils httpUtils;
    private static HttpTools httpTools;

    public static HttpUtils getInstance() {
        if (httpUtils == null) {
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }

    public static HttpTools getHttpTools() {
        if (httpTools == null) {
            httpTools = new HttpTools();
        }
        return httpTools;
    }


    public <T> HttpHandler<String> getDataFromServer(String url, final AppBaseAdapter<T> adapter,
                                                     final List<T> list,
                                                     final boolean isClear, final TypeReference<AppBean<T>> type) {
        HttpHandler<String> httpHandler = HttpTools.getInstance().send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                AppBean<T> app = JSONObject.parseObject(responseInfo.result, type);
                if (isClear) {
                    list.clear();
                }
                list.addAll(app.getResultList());
                adapter.notifyDataSetChanged();
            }
            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
        return httpHandler;
    }
}
